<template>
  <page-header-wrapper :title="false">
    <div>
      <a-row id="home_wrapper" type="flex">
        <a-col id="left_tree" flex="400px">
          <div>
            <a-tree checkable :show-line="true" :show-icon="false" :show-leaf-icon="false" :treeData="orgAllTreeData" :replaceFields="orgTreereplaceFields" @select="onSelectOrgTree">
            </a-tree>
          </div>
        </a-col>
        <div style="width:10px"></div>
        <a-col flex="auto">
          <div id="right-content-white">
            <a-card title="" :bordered="false">
            <div class="table-page-search-wrapper">
              <a-form layout="inline">
                <a-row :gutter="48">
                  <a-col :md="8" :sm="24">
                    <a-form-item label="项目名称">
                      <a-input v-model="orgQueryParam.keyword" placeholder="" :allow-clear="true"/>
                    </a-form-item>
                  </a-col>

                  <a-col :md="8" :sm="24">
                    <span class="table-page-search-submitButtons" >
                      <a-button type="primary" @click="() => initQuery()">查询</a-button>
                      <!-- <a-button style="margin-left: 8px" @click="() => queryOrgParam = {}">重置</a-button> -->
                    </span>
                  </a-col>
                </a-row>
              </a-form>

              <div class="table-operator">
                <a-button type="primary" icon="plus" @click="() => handleAddOrg()">添加</a-button>
                <a-popconfirm
                      title="确认删除所选项目？"
                      ok-text="确认"
                      cancel-text="取消"
                      @confirm="() => delOrg(orgSelectedRowKeys.join(','))"
                    >
                  <a-button v-if="orgSelectedRowKeys.length > 0" type="danger" icon="delete" >批量删除</a-button>
                </a-popconfirm>
              </div>

              <template>
                <a-table
                  size="small"
                  bordered
                  :columns="orgColumns"
                  :row-key="record => record.id"
                  :data-source="orgData"
                  :pagination="orgPagination"
                  :loading="loading"
                  @change="handleOrgTableChange"
                  :row-selection="{ selectedRowKeys: orgSelectedRowKeys, onChange: onOrgSelectChange }"
                >
                  <span slot="orgAction" slot-scope="text, record">
                    <a @click="() => handleEditOrg(record.id)"> <a-icon type="edit" /> 编辑 </a>
                    <a-divider type="vertical" />
                    <a-popconfirm
                      title="确认删除该项目？"
                      ok-text="确认"
                      cancel-text="取消"
                      @confirm="() => delOrg(record.id)"
                    >
                      <a href="#"> <a-icon type="delete" /> 删除</a>
                    </a-popconfirm>
                  </span>
                </a-table>
              </template>
            </div>
            </a-card>
          </div>
        </a-col>
      </a-row>
    </div>

    <a-modal
      :maskClosable="false"
      :title="orgOperType == 'add' ? '添加项目' : '编辑项目'"
      :width="640"
      :visible="!!orgOperType"
      :confirmLoading="loading"
      @ok="() => addOrEditOrg()"
      @cancel="() => cancelAddOrEditOrg()"
      :forceRender="true"
    >
      <a-spin :spinning="loading">
        <a-form ref="orgOperForm" :form="form" v-bind="formLayout" >
          <a-form-item v-show="false" label="主键ID">
            <a-input
              type="hidden"
              v-decorator="[
                'id',
                {
                  rules: [
                    { required: false},
                  ],
                },
              ]"
            />
          </a-form-item>
          <a-form-item v-show="orgOperType == 'add'" label="所属单位" required >
            <a-tree-select
              v-decorator="[
                'orgId',
                {
                  rules: [
                    { required: true, message: '请选择所属单位', validateTrigger: 'blur' },
                  ],
                },
              ]"
              :filterTreeNode="onOrgOperFilter"
              show-search
              :replaceFields="orgTreereplaceFields"
              style="width: 100%"
              :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
              :tree-data="orgAllTreeData"
              placeholder="请选择"
              tree-default-expand-all
              allow-clear
            >
            </a-tree-select>
          </a-form-item>
          <a-form-item label="项目名称" required prop="name">
            <a-input
              v-decorator="[
                'name',
                {
                  rules: [
                    { required: true, message: '请输入项目名称', whitespace: true, validateTrigger: 'blur' },
                    { max: 100, message: '项目名称长度不能超过100', trigger: 'blur' },
                  ],
                },
              ]"
            />
          </a-form-item>
          <a-form-item v-show="orgOperType == 'add'" label="项目编码" required >
            <a-input
              v-decorator="[
                'code',
                {
                  rules: [
                    { required: true, message: '请输入项目编码', whitespace: true, validateTrigger: 'blur' },
                    { max: 100, message: '项目编码长度不能超过100', trigger: 'blur' },
                  ],
                },
              ]"
            />
          </a-form-item>
          <a-form-item label="城市区域" name="regionCode">
            <a-cascader
              v-decorator="['regionCode', { rules: [{ required: false }] }]"
              change-on-select
              :fieldNames="regionTreeReplaceFields"
              :options="regionTreeData"
              placeholder="请选择"
              :showSearch="true"
            />
          </a-form-item>
          <a-form-item label="项目地址" >
            <a-input
              v-decorator="[
                'address',
                {
                  rules: [
                    { required: false},
                    { max: 100, message: '项目地址长度不能超过100', trigger: 'blur' },
                  ],
                },
              ]"
            />
          </a-form-item>
          <a-form-item label="成立时间">
            <a-date-picker
              v-decorator="['regdate', { rules: [{ required: false }] }]"
              type="date"
              placeholder="请选择"
              style="width: 100%;"
              :disabled-date="disabledDate"
            />
          </a-form-item>
          <a-form-item label="项目描述" >
            <a-textarea
              :rows="3"
              v-decorator="[
                'bz',
                {
                  rules: [
                    { required: false},
                    { max: 255, message: '项目描述长度不能超过255', trigger: 'blur' },
                  ],
                },
              ]"
            />
          </a-form-item>
        </a-form>
      </a-spin>
    </a-modal>
  </page-header-wrapper>
</template>

<script>

import { TreeSelect,Cascader } from 'ant-design-vue';
import moment from 'moment';

const orgColumns = [
  {
    title:'项目名称',
    dataIndex: 'name',
    key: 'name'
  },
  {
    title: '所属单位',
    dataIndex: 'orgName',
    key: 'orgName',
  },
  {
    title: '项目编码',
    dataIndex: 'code',
    key: 'code',
  },
  {
    title: '项目地址',
    dataIndex: 'address',
    key: 'address',
  },
  {
    title: '成立时间',
    key: 'regdate',
    dataIndex: 'regdate'
  },
  {
    title: '操作',
    key: 'OrgAction',
    scopedSlots: { customRender: 'orgAction' },
  },
];

export default {
  name: 'ProjectList',
  components: {
      [Cascader.name]: Cascader,
      [TreeSelect.name]: TreeSelect,
      ATreeSelectNode: TreeSelect.TreeNode
  },
  data() {
    return {
      loading: false,
      orgTreeSelect:'',
      orgOperType:'',
      orgOperTreeData: [],
      orgAllTreeData: [],
      orgAllData:[],
      orgTreereplaceFields: {
        title: 'lable',
        key:'id',
        value:'id'
      },
      formLayout : {
        labelCol: { span: 4 },
        wrapperCol: { span: 20 }
      },
      orgColumns,
      orgSelectedRowKeys: [],
      orgQueryParam:{},
      orgPagination: {
        pageSize: 10,
        showQuickJumper: true,
        showTotal: (total, range) => `共 ${total} 条`,
      },
      orgData:[],
      regionTreeData: [],
      regionTreeReplaceFields: {
        value: 'id',
        label: 'lable',
        children: 'children',
      },
      form: this.$form.createForm(this)
    }
  },
  mounted() {
    this.getOrgTree()
    this.getRegionTree()
    this.queryOrgParam()
  },
  methods: {
    disabledDate(current) {
      return current > moment().endOf('day')
    },
    onOrgOperFilter (searchVal, treeNode) {
      return treeNode.data.props.lable.includes(searchVal)
    },
    onSelectOrgTree(selectedKeys, info) {
      this.orgTreeSelect = selectedKeys && selectedKeys.length > 0 ? selectedKeys[0] : '';
      this.orgPagination.current = 1
      this.queryOrgParam();
    },
    getOrgTree() {
      this.$http.get('/account/getOrgTree').then((res) => {
        if(res.code == 0){
          this.orgAllTreeData = res.data
        }
      })
    },
    onOrgSelectChange(selectedRowKeys) {
      this.orgSelectedRowKeys = selectedRowKeys;
    },
    handleOrgTableChange(pagination, filters, sorter) {
      this.orgPagination.current = pagination.current;
      this.orgPagination.pageSize = pagination.pageSize;
      this.queryOrgParam(pagination.current,pagination.pageSize);
    },
    getRegionTree() {
      this.$http.get('/web/dict/getRegionTree').then((res) => {
        if (res.code == 0) {
          this.regionTreeData = res.data
        }
      })
    },
    cancelAddOrEditOrg(){
      this.orgOperType = '';
    },
    handleEditOrg(id){
      this.orgOperType = 'edit';
      const operData = this.orgData.filter(i => i.id == id)[0];
      console.log(operData)
      let tmp = {
        id:operData.id,
        name:operData.name,
        code:operData.code,
        address:operData.address,
        bz:operData.bz
      }
      if(operData.regdate) tmp.regdate = moment(operData.regdate);
      let regionCode = []
      if (operData.province) regionCode.push(operData.province)
      if (operData.city) regionCode.push(operData.city)
      if (operData.district) regionCode.push(operData.district)
      this.form.setFieldsValue(tmp)
    },
    handleAddOrg(){
      let preIsAdd = this.orgOperType == 'add';
      this.orgOperType = 'add'
      if (!preIsAdd) {
        // let tmp = {
        //   id: '',
        //   name: '',
        //   address: '',
        //   sex: '1',
        //   type: 'ADMIN',
        //   orgId:'',
        //   phone:'',
        //   password:''
        // }
        this.form.resetFields()
      }
    },
    addOrEditOrg(){
      //  设置校验参数
      const validateFieldsKey = ['name','code','bz','address','regionCode','id','regdate']
      if(this.orgOperType === 'add'){
        validateFieldsKey.push(...['code','orgId'])
      }

      this.form.validateFields(validateFieldsKey,(error, values) => {
        if (error) return;

        let param = values
        if(param.regdate) param.regdate = param.regdate.format('YYYY-MM-DD');
        if (values.regionCode && values.regionCode.length > 0) {
          if (values.regionCode[0]) param.province = values.regionCode[0]
          if (values.regionCode[1]) param.city = values.regionCode[1]
          if (values.regionCode[2]) param.district = values.regionCode[2]
        }

        this.loading = true;
        this.$http.post(this.orgOperType == 'add' ? '/web/project/add' : '/web/project/update',param).then((res) => {
          this.loading = false;
          if(res.code == 0){
            this.$notification['success']({
              message: '成功',
              description: `项目${this.orgOperType == 'add' ? '添加' : '编辑'}成功`,
            })
            this.orgOperType = '';
            this.queryOrgParam();
          }else{
            this.$notification['error']({
              message: '错误',
              description: res.message,
              duration: 4,
            })
          }
        })

      })

      // this.$refs.orgOperForm.validate(valid => {
      //   if (valid) {

      //   } else {
      //     return false;
      //   }
      // });

    },
    delOrg(id){
      this.loading = true;
      let param = {projectIds:id};
      this.$http.delete('/web/project/delete',{params:param}).then((res) => {
        this.loading = false;
        if(res.code == 0){
          this.$notification['success']({
            message: '成功',
            description: '项目已删除',
          })
          this.orgPagination.current = 1
          this.queryOrgParam();
        }else{
          this.$notification['error']({
            message: '错误',
            description: res.message,
            duration: 4,
          })
        }
      })
    },
    queryOrgParam(){
      this.loading = true;
      let param = Object.assign({},this.orgQueryParam);
      param.pOrgId = this.orgTreeSelect;
      param.start = this.orgPagination.current;
      param.limit = this.orgPagination.size;
      this.$http.get('/web/project/page',{params:param}).then((res) => {
        this.loading = false;
        if(res.code == 0){
          let data = res.data;
          this.orgData = data.records;
          const pagination = { ...this.pagination };
          // Read total count from server
          // pagination.total = data.totalCount;
          pagination.total = data.total;
          pagination.current = data.current;
          pagination.pageSize = data.size;
          this.orgPagination = pagination;
        }
      })
   },
   initQuery(){
     this.orgPagination.current = 1;
     this.queryOrgParam();
   }
  },
}
</script>